package chapter13.eg1.broadcaster;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

public class LogEventBroadcaster {
  private volatile boolean running = true;
  private final EventLoopGroup group;
  private final Bootstrap bootstrap;

  public LogEventBroadcaster(InetSocketAddress address) {
    group = new NioEventLoopGroup();
    bootstrap = new Bootstrap();
    bootstrap.group(group)
        .channel(NioDatagramChannel.class)
        .option(ChannelOption.SO_BROADCAST, true)
        .handler(new LogEventEncoder(address));
  }

  public void run() throws Exception {
    Channel ch = bootstrap.bind(0).syncUninterruptibly().channel();

    String filePath = "test.txt";
    for (int i = 0; running; i++) {
      String line = "test-line-" + i;
      LogEvent logEvent = new LogEvent(null, filePath, line, -1);
      ch.writeAndFlush(logEvent);
      System.out.println("broadcast line: " + line);
      TimeUnit.SECONDS.sleep(1);
    }
  }

  public void stop() {
    running = false;
    group.shutdownGracefully();
  }

  public static void main(String[] args) throws Exception {
    LogEventBroadcaster broadcaster = new LogEventBroadcaster(
        new InetSocketAddress("255.255.255.255", 9999));
    broadcaster.run();
  }

}
